#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_err.h"
#include "esp_sntp.h"

#include "cJSON.h"
#include "sntp.h"
#include "http_client.h"



#define TIME_URL        "https://api.uukit.com/time"

static const char* TAG = "ntp";


void time_sync_notification_cb(struct timeval *tv)
{
    ESP_LOGI(TAG, "Notification of a time synchronization event");
}

void init_sntp(void)
{
    ESP_LOGI(TAG, "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "pool.ntp.org");
    sntp_set_time_sync_notification_cb(time_sync_notification_cb);
    sntp_init();
}


void obtain_time(void)
{
    /**
     * NTP server address could be aquired via DHCP,
     * see LWIP_DHCP_GET_NTP_SRV menuconfig option
     */
#ifdef LWIP_DHCP_GET_NTP_SRV
    sntp_servermode_dhcp(1);
#endif

    init_sntp();

    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = { 0 };
    int retry = 0;
    const int retry_count = 10;
    while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
        ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
        vTaskDelay(2000 / portTICK_PERIOD_MS);
    }
    time(&now);
    localtime_r(&now, &timeinfo);
}

/*
{
status: 1,
data: {
    timestamp: 1656418615,
    microtime: 1656418615.157257,
    gmt: "2022-06-28 12:16:55",
    utc: "2022-06-28T12:16:55Z",
    timezone: "Shanghai"
},
req_id: "09377f2bb6f24f1b4923"
}

*/
esp_err_t get_ntp_time(char* time_str)
{
    size_t buf_size = 512;
    char http_data[buf_size];
    memset(http_data, 0, buf_size);
    esp_err_t err = https_get_with_url(TIME_URL, (char*)http_data);
    if(err != ESP_OK) {
        ESP_LOGW(TAG, "get npt url failed");
        return err;
    }
    printf("data buf len=%d\n", strlen(http_data));
    
    memset(time_str, 0, 32);

    cJSON *root = cJSON_Parse(http_data);   
    if(root != NULL)
    {
        cJSON *time = cJSON_GetObjectItem(root,"data");
        time = cJSON_GetObjectItem(time, "gmt");
        char *t = cJSON_GetStringValue(time);
        if(t==NULL)
        {
            ESP_LOGI(TAG, "time error");
            return -1;
        }else{
            ESP_LOGI(TAG, "time = %s",t);
            strncpy(time_str, t, 25);   //将字符串复制到str_time
        }
    }
    cJSON_Delete(root);
    ESP_LOGI(TAG, "NTP time: %s", time_str);
    return ESP_OK;
}
